package com.blue.base.oauth.gateway.config.filters;

import com.blue.base.common.id.IDGenerator;
import com.blue.base.common.constants.GatewayHeaderKey;
import com.blue.base.gateway.starter.utils.ReactiveAddrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 请求头部处理器
 *
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Component
public class RequestHeaderAddFilter extends AbstractWebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("3.过滤器链-添加请求序列号、请求客户端IP头部信息");
        ServerHttpRequest request = exchange.getRequest();
        // 该实例为只读实例，如果直接操作add等方法会报错
        HttpHeaders headers = request.getHeaders();
        String serialNum = headers.getFirst(GatewayHeaderKey.REQUEST_NO);
        if (StringUtils.isEmpty(serialNum)) {
            serialNum = IDGenerator.getIdStr();
            ServerHttpRequest newReq = request.mutate()
                    .header(GatewayHeaderKey.REQUEST_NO, serialNum)
                    .header(GatewayHeaderKey.REMOTE_IP, ReactiveAddrUtil.getRemoteAddr(request))
                    .build();
            ServerWebExchange webExchange = exchange.mutate().request(newReq).build();
            return chain.filter(webExchange);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -90;
    }
}
